#include "extendedcombobox.h"
#include <QAbstractItemView>
#include <QFontMetrics>
#include <QScrollBar>

ExtendedComboBox::ExtendedComboBox(QWidget *parent)
    : QComboBox(parent)
{
    view()->setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);
    view()->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
}

void ExtendedComboBox::showPopup()
{
    QComboBox::showPopup(); // 先调用基类方法
    QAbstractItemView *view = this->view();
    view->setFixedWidth(calculateMaxItemWidth(view));
}

int ExtendedComboBox::calculateMaxItemWidth(QAbstractItemView *view)
{
    int maxWidth = 0;
    QFontMetrics fm(view->font());
    const int iconWidth = iconSize().width();

    int w = count();
    for(int i = 0; i < count(); ++i)
    {
        QString str = itemText(i);
        int textWidth = fm.horizontalAdvance(itemText(i));
        if(!itemIcon(i).isNull())
            textWidth += iconWidth + 4; // 图标+间距

        maxWidth = qMax(maxWidth, textWidth);
    }
    maxWidth+=50;
    // 处理边距和滚动条
    int left, right;
    view->getContentsMargins(&left, nullptr, &right, nullptr);
    maxWidth += left + right;

    if(view->verticalScrollBar()->isVisible())
        maxWidth += view->verticalScrollBar()->width();
    w = width();
    return qMax(maxWidth, width()); // 至少等于当前宽度
}
